package PluginFactory

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"kubehark/kubehark-framwork/pkg/Plugin/Plugins"
	logger "kubehark/kubehark-framwork/pkg/Plugin/Plugins/Logger"
	"kubehark/kubehark-framwork/pkg/Plugin/Plugins/Oidc"
	"kubehark/kubehark-framwork/pkg/Plugin/Plugins/Opa"
)

var PluginFa *PluginFactory

type PluginFactory struct {
	BeforePlugins []string
	AfterPlugins  []string
	PluginsMap    map[string]Plugins.PluginInterface
}

func InitPluginFactory(configmap map[string]interface{}) {
	for k, v := range configmap {
		AddPlugin(k, PluginFa.PluginsMap[k].SetConfigFromInterface(v))
	}
}

// 初始化插件
func AddPlugin(name string, plugin Plugins.PluginInterface) {
	PluginFa.PluginsMap[name] = plugin
}

// 设置使用前置插件
func SetBefoUsePlugin(plugins []string) {
	PluginFa.BeforePlugins = plugins
}

// 设置使用后置插件
func SetAfterPlugin(plugins []string) {
	PluginFa.AfterPlugins = plugins
}

func RunBeforPlugin(c *gin.Context) error {
	// 运行所有前置插件逻辑 TODO
	for _, v := range PluginFa.BeforePlugins {
		fmt.Println("前置"+v)
		if !c.IsAborted(){
			if err := PluginFa.PluginsMap[v].RunPlugin(c); err != nil {
				return err
			}
		}

	}
	return nil
}

func RunAfterPlugin(c *gin.Context) error {
	// 运行所有后置插件逻辑 TODO
	for _, v := range PluginFa.AfterPlugins {
		if !c.IsAborted(){
			fmt.Println("后置"+v)
			if err := PluginFa.PluginsMap[v].RunPlugin(c); err != nil {
				return err
			}
		}

	}
	return nil
}

func init() {
	PluginFa = &PluginFactory{
		BeforePlugins: []string{},
		AfterPlugins:  []string{},
		PluginsMap: map[string]Plugins.PluginInterface{
			"log": &logger.LoggerPlugin{},
			"oidc": &Oidc.OidcPlugin{},
			"opa" : &Opa.OpaPlugin{},
		},
	}
}
